/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// 法一：bfs
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        deque<TreeNode*> q;
        q.push_back(root);
        while (!q.empty()) {
            int len = q.size();
            res.push_back(q.back()->val);
            for (int i = 0; i < len; ++i) {
                TreeNode* tmp = q.front();
                q.pop_front();
                if (tmp->left) q.push_back(tmp->left);
                if (tmp->right) q.push_back(tmp->right);
            }
        }
        return res;
    }
};

// 法二：dfs，遍历时先遍历右节点，可以保证每层最先访问的都是最右边的节点
class Solution {
public:
    void dfs(TreeNode* root, int depth, vector<int>& res) {
        if (!root) return;
        if (res.size() == depth) { // 该深度下当前节点是第一个被访问的节点
            res.push_back(root->val);
        }
        dfs(root->right, depth + 1, res);
        dfs(root->left, depth + 1, res);
    }
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        dfs(root, 0, res);
        return res;
    }
};

